package com.jackchong.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;

import com.hjq.language.MultiLanguages;
import com.jackchong.utils.JAuto;
import com.jackchong.utils.ThreadUtils;


;


/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2017/10/16
 */

public class BaseToolsActivity extends SwipeBackActivity implements ActivityHelper {

    protected BaseToolsActivity mActivity;
    private int mCurrentOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    private SensorManager mSensorManager;
    private OrientationListener mOrientationListener;
    private boolean isAutoRotate = false;

    private Runnable mHideInputKeyRunnable;
    protected Handler mHandler = new Handler();


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = this;
        AppManager.getInstance().addActivity(this);
        initEvent();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(MultiLanguages.attach(newBase));
    }

    private void initEvent() {
        registerReceiver(mEventReceiver, new IntentFilter("jackchong"));
    }

    private final BroadcastReceiver mEventReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            EventMgsBean bean = new EventMgsBean() {
                @Override
                public int getKey() {
                    return intent.getIntExtra("key", 0);
                }

                @Override
                public Object getValue() {
                    return null;
                }
            };
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                if (fragment instanceof BaseFragment){
                    ((BaseFragment) fragment).onSendEvent(bean);
                }
            }
            onSendEvent(bean);
        }
    };

    protected void openGravityListener(){
        mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        mOrientationListener = new OrientationListener(this::onGravityChange);
        mSensorManager.registerListener(mOrientationListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }


    public void openAutoRotate(){
        isAutoRotate = true;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }

    public void closeAutoRotate(){
        isAutoRotate = false;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    @Override
    public void setWindowFILL(boolean fill){
        if (fill){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            return;
        }
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public View inflateView(@LayoutRes int layout){
        return View.inflate(mActivity, layout, null);
    }
    @Override
    public View inflateView(@LayoutRes int layout, boolean auto){
        View view = inflateView(layout);
        JAuto.auto(view);
        return view;
    }

    @Override
    public void openSerivce(Class cls){
        startService(new Intent(mActivity, cls));
    }

    @Override
    public void openActivity(Class cls){
        openActivity(new Intent(mActivity, cls), false);
    }
    @Override
    public void openActivity(Class cls, boolean finish){
        openActivity(new Intent(mActivity, cls), finish);
    }
    @Override
    public void openActivity(Intent intent){
        openActivity(intent, null, false);
    }

    @Override
    public void openActivity(Intent intent, boolean finish){
        openActivity(intent,null, finish);
    }

    @Override
    public void openActivity(Intent intent, @Nullable Bundle options, boolean finish){
        startActivity(intent, options);
        if (finish) finishActivity();
    }

    @Override
    public void openActivityForResult(Intent intent, int requestCode){
        startActivityForResult(intent,requestCode);
    }

    @Override
    public void openActivityForResult(Class cls, int requestCode){
        openActivityForResult(new Intent(mActivity, cls), requestCode);
    }

    @Override
    public void finishActivity(){
        hideInputKeyVisibility();
        finish();
    }

    @Override
    public void finishActivity(long delay) {
        ThreadUtils.postDelay(delay, () -> {
            if (!isFinishing()) {
                finishActivity();
            }
        });
    }


    @Override
    public @ColorInt
    int getColorResources(@ColorRes int id){
        return getResources().getColor(id);
    }




    @Override
    public void hideInputKeyVisibility() {
        hideInputKeyVisibility(0);
    }

    @Override
    public void hideInputKeyVisibility(long delay) {
     /*   if (!getInputKeyVisibility()){
            return;
        }*/
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mHideInputKeyRunnable = () -> {
            if (getInputKeyVisibility()) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            }
        };
        mHandler.postDelayed(mHideInputKeyRunnable, delay);
    }

    @Override
    public void showInputKeyVisibility(EditText anchor) {
        anchor.requestFocus();
        anchor.setCursorVisible(true);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mHandler.postDelayed(() -> {
            imm.showSoftInput(anchor, InputMethodManager.SHOW_FORCED);
        }, 200);
    }


    public void cancelHideInputKey() {
        mHandler.removeCallbacks(mHideInputKeyRunnable);
    }


    @Override
    public boolean getInputKeyVisibility(){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isActive();
    }


    /**
     * 设置屏幕方向
     * @param isPortrait true 为竖屏, false为横屏
     */
    public void setScreenOrientation(boolean isPortrait){
        int orientation = isPortrait ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        mCurrentOrientation = orientation;
        isAutoRotate = false;
        setRequestedOrientation(orientation);
    }

    @Override
    public void onReceiveEvent(EventMgsBean event) {

    }

    @Override
    public final void onSendEvent(EventMgsBean event) {
        runOnUiThread(() -> onReceiveEvent(event));
    }

    /**
     * 获取屏幕方向
     * @return true 为竖屏, false为横屏
     */
    public boolean isScreenOrientation(){
        return getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE;
    }


    /**
     * time    : 2019/4/21 12:29
     * desc    : 当屏幕方向改变时
     * versions: 1.0
     */
    protected void onGravityChange(OrientationEnum newOrientation){

    }


    @Override
    protected void onResume() {
        if (!isAutoRotate){
            if(getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && mCurrentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){  //不等于竖屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }else if(getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && mCurrentOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mEventReceiver);
        if (mSensorManager != null){
            mSensorManager.unregisterListener(mOrientationListener);
        }
        System.gc();
        AppManager.getInstance().removeActivity(this);
    }

}
